package com.jingxuan.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jingxuan.dto.request.RecordVisitRequest;
import com.jingxuan.dto.request.RecordLinkClickRequest;
import com.jingxuan.dto.response.VisitStatsResponse;
import com.jingxuan.dto.response.VisitStatsResponse.DailyStatsItem;
import com.jingxuan.entity.PageVisit;
import com.jingxuan.entity.LinkClick;
import com.jingxuan.entity.DailyStats;
import com.jingxuan.mapper.VisitStatsMapper;
import com.jingxuan.service.VisitStatsService;

import lombok.extern.slf4j.Slf4j;

/**
 * 访问统计服务实现
 */
@Slf4j
@Service
public class VisitStatsServiceImpl implements VisitStatsService {

    @Autowired
    private VisitStatsMapper visitStatsMapper;

    // 缓存最后更新时间
    private LocalDateTime lastRefreshTime = LocalDateTime.now();

    @Override
    @Transactional
    public void recordPageVisit(RecordVisitRequest request, String ipAddress, String userAgent, Long userId) {
        LocalDate today = LocalDate.now();
        
        PageVisit pageVisit = new PageVisit();
        pageVisit.setVisitorId(request.getVisitorId());
        pageVisit.setUserId(userId);
        pageVisit.setIpAddress(ipAddress);
        pageVisit.setUserAgent(userAgent);
        pageVisit.setPageUrl(request.getPageUrl());
        pageVisit.setReferer(request.getReferer());
        pageVisit.setVisitDate(today);
        pageVisit.setVisitTime(LocalDateTime.now());

        visitStatsMapper.insertPageVisit(pageVisit);
        log.debug("记录页面访问: visitorId={}, pageUrl={}", request.getVisitorId(), request.getPageUrl());

        // 更新每日统计
        updateDailyUvStats(today);
    }

    @Override
    @Transactional
    public void recordLinkClick(RecordLinkClickRequest request, Long userId) {
        LocalDate today = LocalDate.now();
        
        LinkClick linkClick = new LinkClick();
        linkClick.setVisitorId(request.getVisitorId());
        linkClick.setUserId(userId);
        linkClick.setProductId(request.getProductId());
        linkClick.setLinkUrl(request.getLinkUrl());
        linkClick.setPlatformId(request.getPlatformId());
        linkClick.setClickDate(today);
        linkClick.setClickTime(LocalDateTime.now());

        visitStatsMapper.insertLinkClick(linkClick);
        log.debug("记录链接跳转: visitorId={}, productId={}", request.getVisitorId(), request.getProductId());

        // 增加每日跳转统计
        visitStatsMapper.incrementDailyLinkClickCount(today);
    }

    @Override
    public VisitStatsResponse getVisitStats(String period) {
        LocalDate today = LocalDate.now();
        LocalDate startDate;

        // 根据周期计算起始日期
        switch (period) {
            case "30d":
                startDate = today.minusDays(29);
                break;
            case "quarter":
                startDate = today.minusDays(89);
                break;
            case "year":
                startDate = today.minusDays(364);
                break;
            case "6d":
            default:
                startDate = today.minusDays(5);
                break;
        }

        // 获取今日实时统计
        int todayUv = visitStatsMapper.countUvByDate(today);
        int todayClicks = visitStatsMapper.countLinkClicksByDate(today);

        // 获取历史统计数据
        List<DailyStats> uvStats = visitStatsMapper.selectUvStatsByDateRange(startDate, today);
        List<DailyStats> clickStats = visitStatsMapper.selectLinkClickStatsByDateRange(startDate, today);

        // 合并UV和点击数据
        Map<LocalDate, DailyStatsItem> statsMap = new HashMap<>();
        
        // 初始化所有日期
        LocalDate current = startDate;
        DateTimeFormatter formatter = period.equals("year") ? 
            DateTimeFormatter.ofPattern("yyyy-MM-dd") : DateTimeFormatter.ofPattern("MM-dd");
        
        while (!current.isAfter(today)) {
            statsMap.put(current, DailyStatsItem.builder()
                .date(current.format(formatter))
                .uvCount(0)
                .linkClickCount(0)
                .build());
            current = current.plusDays(1);
        }

        // 填充UV数据
        for (DailyStats stat : uvStats) {
            if (stat.getStatDate() != null && statsMap.containsKey(stat.getStatDate())) {
                DailyStatsItem item = statsMap.get(stat.getStatDate());
                item.setUvCount(stat.getUvCount() != null ? stat.getUvCount() : 0);
            }
        }

        // 填充点击数据
        for (DailyStats stat : clickStats) {
            if (stat.getStatDate() != null && statsMap.containsKey(stat.getStatDate())) {
                DailyStatsItem item = statsMap.get(stat.getStatDate());
                item.setLinkClickCount(stat.getLinkClickCount() != null ? stat.getLinkClickCount() : 0);
            }
        }

        // 转换为有序列表
        List<DailyStatsItem> dailyStatsList = new ArrayList<>();
        current = startDate;
        while (!current.isAfter(today)) {
            dailyStatsList.add(statsMap.get(current));
            current = current.plusDays(1);
        }

        // 计算上次更新距离现在的分钟数
        int minutesSinceRefresh = (int) ChronoUnit.MINUTES.between(lastRefreshTime, LocalDateTime.now());

        return VisitStatsResponse.builder()
            .todayUv(todayUv)
            .todayLinkClicks(todayClicks)
            .lastUpdateMinutes(minutesSinceRefresh)
            .dailyStats(dailyStatsList)
            .build();
    }

    @Override
    @Transactional
    public void refreshDailyStats() {
        LocalDate today = LocalDate.now();
        
        int uvCount = visitStatsMapper.countUvByDate(today);
        int pvCount = visitStatsMapper.countPvByDate(today);
        int clickCount = visitStatsMapper.countLinkClicksByDate(today);

        DailyStats stats = new DailyStats();
        stats.setStatDate(today);
        stats.setUvCount(uvCount);
        stats.setPvCount(pvCount);
        stats.setLinkClickCount(clickCount);

        visitStatsMapper.upsertDailyStats(stats);
        lastRefreshTime = LocalDateTime.now();
        
        log.info("刷新每日统计: date={}, uv={}, pv={}, clicks={}", today, uvCount, pvCount, clickCount);
    }

    /**
     * 更新每日UV统计
     */
    private void updateDailyUvStats(LocalDate date) {
        int uvCount = visitStatsMapper.countUvByDate(date);
        int pvCount = visitStatsMapper.countPvByDate(date);
        
        DailyStats stats = new DailyStats();
        stats.setStatDate(date);
        stats.setUvCount(uvCount);
        stats.setPvCount(pvCount);
        stats.setLinkClickCount(0);

        visitStatsMapper.upsertDailyStats(stats);
    }
}

